package com.nineclock.common.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@WebFilter(urlPatterns = "/*")
public class CurrentUserFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            //获取 安全框架 上下文对象
            SecurityContext context = SecurityContextHolder.getContext();
            //获取认证对象
            Authentication authentication = context.getAuthentication();
            //获取到用户信息
            String name = authentication.getName();
            //如果没有登录，获取到的是 anonymousUser（匿名用户）
            if(StrUtil.isNotEmpty(name) && !"anonymousUser".equals(name)){
                //转换 java 对象
                UserInfo userInfo = JSONUtil.toBean(name, UserInfo.class);

                //存储到当前线程
                CurrentUserHolder.set(userInfo);
            }
            //放行
            chain.doFilter(request, response);
        } finally {
            //执行完业务方法后，才会执行
            CurrentUserHolder.remove();
        }


    }
    
    
}
